<template>
  <div class="grade-management">
    <h2>成绩管理</h2>
    
    <!-- 成绩统计卡片 -->
    <div class="statistics-cards" v-if="role === 'STUDENT'">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card shadow="hover" class="stat-card">
            <div class="stat-value">{{ gradeStats.totalCourses || 0 }}</div>
            <div class="stat-label">总课程数</div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover" class="stat-card">
            <div class="stat-value">{{ gradeStats.passedCourses || 0 }}</div>
            <div class="stat-label">通过课程</div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover" class="stat-card">
            <div class="stat-value">{{ formatNumber(gradeStats.averageGrade) || '0.0' }}</div>
            <div class="stat-label">平均成绩</div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover" class="stat-card">
            <div class="stat-value">{{ formatNumber(gradeStats.totalCredits) || '0.0' }}</div>
            <div class="stat-label">总学分</div>
          </el-card>
        </el-col>
      </el-row>
    </div>
    
    <!-- 学生成绩表格 -->
    <div class="grade-table" v-if="role === 'STUDENT'">
      <div class="table-header">
        <h3>我的成绩</h3>
        <div class="filter-bar">
          <el-input
            v-model="searchQuery"
            placeholder="搜索课程名称"
            style="width: 200px; margin-right: 10px"
            clearable
            @input="handleSearch"
          />
          <el-select v-model="semesterFilter" placeholder="学期筛选" clearable @change="handleSearch">
            <el-option label="2024春季" value="2024春季" />
            <el-option label="2024秋季" value="2024秋季" />
            <el-option label="2025春季" value="2025春季" />
          </el-select>
        </div>
      </div>
      
      <el-table :data="filteredGrades" style="width: 100%" v-loading="loading">
        <el-table-column prop="courseName" label="课程名称">
          <template #default="scope">
            <span>
              {{ scope.row.courseName }}<span v-if="scope.row.semester && scope.row.semester.includes('补考')">(补考)</span>
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="semester" label="学期" width="120" />
        <el-table-column prop="regularGrade" label="平时成绩" width="100">
          <template #default="scope">
            {{ scope.row.regularGrade !== null ? scope.row.regularGrade : '未录入' }}
          </template>
        </el-table-column>
        <el-table-column prop="examGrade" label="期末成绩" width="100">
          <template #default="scope">
            {{ scope.row.examGrade !== null ? scope.row.examGrade : '未录入' }}
          </template>
        </el-table-column>
        <el-table-column prop="finalGrade" label="最终成绩" width="100">
          <template #default="scope">
            <span :class="getGradeClass(scope.row.finalGrade)">
              {{ scope.row.finalGrade !== null ? (scope.row.displayFinalGrade !== undefined ? scope.row.displayFinalGrade : scope.row.finalGrade) : '未录入' }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="credits" label="学分" width="80">
          <template #default="scope">
            <span :class="{ 'earned-credits': scope.row.finalGrade >= 60 || scope.row.makeupPassed }">
              {{ scope.row.credits }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="100">
          <template #default="scope">
            <el-tag 
              :type="scope.row.status === '补考通过' ? 'success' : 
                    (scope.row.status === '补考未通过' ? 'danger' : 
                     (scope.row.finalGrade >= 60 ? 'success' : 'danger'))" 
              v-if="scope.row.finalGrade !== null"
            >
              {{ scope.row.status || (scope.row.finalGrade >= 60 ? '通过' : '未通过') }}
            </el-tag>
            <el-tag type="info" v-else>未评分</el-tag>
          </template>
        </el-table-column>
      </el-table>
    </div>
    
    <!-- 教师成绩管理 -->
    <div class="teacher-grade-management" v-if="role === 'TEACHER'">
      <div class="course-selection">
        <h3>选择课程</h3>
        <el-select v-model="selectedCourseId" placeholder="请选择课程" @change="handleCourseChange">
          <el-option
            v-for="course in teacherCourses"
            :key="course.id"
            :label="course.name"
            :value="course.id"
          />
        </el-select>
      </div>
      
      <div class="student-grades" v-if="selectedCourseId">
        <div class="table-header">
          <h3>学生成绩列表</h3>
          <div class="action-buttons">
            <el-button type="primary" @click="saveAllGrades" :disabled="!hasChanges">保存所有更改</el-button>
          </div>
        </div>
        
        <el-table :data="courseStudents" style="width: 100%" v-loading="loading">
          <el-table-column label="学号" width="120">
            <template #default="scope">
              {{ scope.row.studentNumber || '无学号' }}
            </template>
          </el-table-column>
          <el-table-column label="姓名" width="120">
            <template #default="scope">
              {{ scope.row.studentName || '无姓名' }}
            </template>
          </el-table-column>
          <el-table-column label="平时成绩" width="150">
            <template #default="scope">
              <el-input-number
                v-model="scope.row.regularGrade"
                :min="0"
                :max="100"
                :precision="1"
                :step="0.5"
                @change="handleGradeChange(scope.row)"
              />
            </template>
          </el-table-column>
          <el-table-column label="期末成绩" width="150">
            <template #default="scope">
              <el-input-number
                v-model="scope.row.examGrade"
                :min="0"
                :max="100"
                :precision="1"
                :step="0.5"
                @change="handleGradeChange(scope.row)"
              />
            </template>
          </el-table-column>
          <el-table-column label="最终成绩" width="150">
            <template #default="scope">
              <span :class="getGradeClass(scope.row.finalGrade)">
                {{ calculateFinalGrade(scope.row) }}
              </span>
            </template>
          </el-table-column>
          <el-table-column label="状态" width="100">
            <template #default="scope">
              <el-tag :type="getStatusType(scope.row)">
                {{ getStatusText(scope.row) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="150">
            <template #default="scope">
              <el-button
                type="primary"
                size="small"
                @click="saveGrade(scope.row)"
                :disabled="!isGradeChanged(scope.row)"
              >
                保存
              </el-button>
              <el-button
                type="danger"
                size="small"
                @click="resetGrade(scope.row)"
                :disabled="!isGradeChanged(scope.row)"
              >
                重置
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    
    <!-- 管理员成绩管理 -->
    <div class="admin-grade-management" v-if="role === 'ADMIN'">
      <div class="filter-section">
        <h3>学生成绩管理</h3>
        <div class="filter-bar">
          <el-input
            v-model="adminSearchQuery"
            placeholder="搜索学生姓名/学号"
            style="width: 200px; margin-right: 10px"
            clearable
            @input="handleAdminSearch"
          />
          <el-select v-model="adminSemesterFilter" placeholder="学期筛选" clearable @change="handleAdminSearch">
            <el-option label="2024春季" value="2024春季" />
            <el-option label="2024秋季" value="2024秋季" />
            <el-option label="2025春季" value="2025春季" />
          </el-select>
        </div>
      </div>
      
      <el-table 
        :data="filteredStudents" 
        style="width: 100%" 
        v-loading="adminLoading"
        row-class-name="student-row"
      >
        <el-table-column prop="studentNumber" label="学号" width="120" fixed="left" />
        <el-table-column prop="studentName" label="姓名" width="120" fixed="left" />
        <el-table-column prop="major" label="专业" width="150" />
        <el-table-column prop="grade" label="年级" width="80" />
        
        <template v-for="course in adminCourses" :key="course.id">
          <el-table-column :label="course.name" :prop="'course_' + course.id" width="120" align="center">
            <template #default="scope">
              <span 
                :class="{
                  'failed-grade': !scope.row['makeupPassed_' + course.id] && 
                                scope.row['course_' + course.id] !== null && 
                                scope.row['course_' + course.id] !== undefined && 
                                scope.row['course_' + course.id] < 60
                }"
              >
                {{ scope.row['course_' + course.id] !== undefined ? 
                   (scope.row['course_' + course.id] !== null ? scope.row['course_' + course.id] : '未录入') : 
                   '未选课' }}
                <span v-if="scope.row['semester_' + course.id] && scope.row['semester_' + course.id].includes('补考')">(补考)</span>
                <el-tag v-if="scope.row['makeupPassed_' + course.id]" size="small" type="success">补考通过</el-tag>
                <el-tag v-if="scope.row['makeupFailed_' + course.id]" size="small" type="danger">补考未通过</el-tag>
              </span>
            </template>
          </el-table-column>
        </template>
        
        <el-table-column label="通过率" width="100" align="center">
          <template #default="scope">
            {{ formatNumber(scope.row.passRate) }}%
          </template>
        </el-table-column>
        <el-table-column label="平均分" width="100" align="center">
          <template #default="scope">
            {{ formatNumber(scope.row.averageGrade) }}
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'

export default {
  name: 'GradeManagement',
  props: {
    userId: {
      type: [Number, String],
      required: true
    },
    role: {
      type: String,
      required: true
    }
  },
  setup(props) {
    // 学生相关数据
    const studentGrades = ref([])
    const gradeStats = ref({})
    
    // 教师相关数据
    const teacherCourses = ref([])
    const selectedCourseId = ref('')
    const courseStudents = ref([])
    const originalGrades = ref({}) // 用于跟踪变更
    
    // 通用数据
    const loading = ref(false)
    const searchQuery = ref('')
    const semesterFilter = ref('')
    const hasChanges = ref(false)
    
    // 管理员相关变量
    const adminStudents = ref([])
    const adminCourses = ref([])
    const adminLoading = ref(false)
    const adminSearchQuery = ref('')
    const adminSemesterFilter = ref('')
    
    // 过滤学生成绩
    const filteredGrades = computed(() => {
      if (!studentGrades.value || studentGrades.value.length === 0) {
        return [];
      }

      // 按课程ID分组
      const courseGroups = {};
      
      // 首先将所有成绩按课程ID分组
      for (const grade of studentGrades.value) {
        if (!courseGroups[grade.courseId]) {
          courseGroups[grade.courseId] = [];
        }
        courseGroups[grade.courseId].push(grade);
      }
      
      // 处理每个课程的成绩，优先使用补考成绩（如果补考通过）
      const processedGrades = [];
      for (const courseId in courseGroups) {
        const grades = courseGroups[courseId];
        
        // 找出原始成绩和补考成绩
        let originalGrade = null;
        let makeupGrade = null;
        
        for (const grade of grades) {
          if (grade.semester && grade.semester.includes('补考')) {
            makeupGrade = grade;
          } else {
            originalGrade = grade;
          }
        }
        
        // 确定显示哪个成绩
        if (makeupGrade) {
          // 有补考成绩，检查是否通过
          const displayGrade = { ...makeupGrade };
          if (makeupGrade.finalGrade >= 60) {
            displayGrade.makeupPassed = true;
            displayGrade.status = '补考通过';
          } else {
            displayGrade.makeupPassed = false;
            displayGrade.status = '补考未通过';
          }
          processedGrades.push(displayGrade);
        } else if (originalGrade) {
          // 没有补考，显示原始成绩
          originalGrade.makeupPassed = false;
          processedGrades.push(originalGrade);
        }
      }
      
      // 应用搜索和筛选
      let result = processedGrades;
      if (searchQuery.value) {
        result = result.filter(grade => 
          grade.courseName && grade.courseName.toLowerCase().includes(searchQuery.value.toLowerCase())
        );
      }
      if (semesterFilter.value) {
        result = result.filter(grade => {
          // 对于补考成绩，我们需要去掉"-补考"后缀进行比较
          const baseSemester = grade.semester ? grade.semester.replace('-补考', '') : '';
          return baseSemester === semesterFilter.value;
        });
      }
      
      console.log('处理后的成绩数据:', result);
      return result;
    })
    
    // 管理员筛选后的学生列表
    const filteredStudents = computed(() => {
      let result = [...adminStudents.value]
      
      if (adminSearchQuery.value) {
        const query = adminSearchQuery.value.toLowerCase()
        result = result.filter(student => 
          (student.studentNumber && student.studentNumber.toLowerCase().includes(query)) ||
          (student.studentName && student.studentName.toLowerCase().includes(query))
        )
      }
      
      if (adminSemesterFilter.value) {
        // 筛选有选定学期课程的学生
        result = result.filter(student => {
          for (const course of adminCourses.value) {
            if (course.semester === adminSemesterFilter.value && 
                student['course_' + course.id] !== undefined) {
              return true
            }
          }
          return false
        })
      }
      
      return result
    })
    
    // 获取学生成绩
    const fetchStudentGrades = async () => {
      if (props.role !== 'STUDENT') return
      
      loading.value = true
      try {
        // 确保studentId是字符串类型
        const studentIdStr = props.userId.toString();
        
        // 获取成绩列表
        const gradesResponse = await axios.get(`/api/users/me/grades?studentId=${studentIdStr}`)
        studentGrades.value = gradesResponse.data
        
        // 获取成绩统计
        const statsResponse = await axios.get(`/api/users/me/grade-statistics?studentId=${studentIdStr}`)
        gradeStats.value = statsResponse.data
        
        console.log('获取到的学生成绩:', studentGrades.value);
        console.log('获取到的成绩统计:', gradeStats.value);
        
        // 处理补考通过的课程
        processMakeupExams(studentIdStr);
      } catch (error) {
        console.error('获取学生成绩失败:', error)
        ElMessage.error('获取成绩信息失败')
      } finally {
        loading.value = false
      }
    }
    
    // 处理补考通过的课程
    const processMakeupExams = async (studentIdStr) => {
      try {
        // 获取补考申请状态
        const makeupResponse = await axios.get(`/api/makeup-exam/student?studentId=${studentIdStr}`)
        const makeupExams = makeupResponse.data || []
        
        console.log('获取到的补考信息:', makeupExams);
        
        // 标记补考通过的课程
        const makeupStatusMap = {}
        makeupExams.forEach(exam => {
          if (exam.status === '补考通过' || exam.status === '补考未通过') {
            makeupStatusMap[exam.courseId] = {
              status: exam.status,
              score: exam.makeupScore
            }
          }
        })
        
        // 更新成绩状态
        studentGrades.value = studentGrades.value.map(grade => {
          const makeupInfo = makeupStatusMap[grade.courseId]
          if (makeupInfo) {
            // 如果是补考成绩记录，保持原样
            if (grade.semester && grade.semester.includes('补考')) {
              return grade
            }
            
            // 如果是原始成绩记录，根据补考状态更新
            if (makeupInfo.status === '补考通过') {
              return { 
                ...grade, 
                makeupPassed: true,
                status: '补考通过',
                // 补考通过时，在统计中按60分计算
                displayFinalGrade: 60,
                finalGrade: 60 // 显示成绩为60
              }
            } else if (makeupInfo.status === '补考未通过') {
              return { 
                ...grade, 
                makeupPassed: false,
                status: '补考未通过',
                // 补考未通过时，保持原成绩
                displayFinalGrade: grade.finalGrade
              }
            }
          }
          return grade
        })
        
        console.log('处理补考后的成绩:', studentGrades.value);
        
        // 手动更新统计数据，确保补考通过的课程被正确计入
        let passedCourses = 0;
        let totalGradePoints = 0;
        let totalCredits = 0;
        let totalCourses = 0;
        
        // 按课程ID分组，避免重复计算
        const courseGroups = {};
        studentGrades.value.forEach(grade => {
          if (!courseGroups[grade.courseId]) {
            courseGroups[grade.courseId] = [];
          }
          courseGroups[grade.courseId].push(grade);
        });
        
        // 处理每个课程，优先使用补考成绩
        for (const courseId in courseGroups) {
          const grades = courseGroups[courseId];
          let bestGrade = null;
          
          // 找出最佳成绩（优先补考通过，其次是最高分）
          for (const grade of grades) {
            if (grade.status === '补考通过') {
              bestGrade = grade;
              break;
            } else if (!bestGrade || (grade.finalGrade > bestGrade.finalGrade)) {
              bestGrade = grade;
            }
          }
          
          if (bestGrade) {
            totalCourses++;
            
            // 计算是否通过
            const isPassed = bestGrade.status === '补考通过' || bestGrade.finalGrade >= 60;
            if (isPassed) {
              passedCourses++;
              totalCredits += parseFloat(bestGrade.credits || 0);
            }
            
            // 计算平均分（补考通过按60分计算）
            if (bestGrade.status === '补考通过') {
              totalGradePoints += 60;
            } else {
              totalGradePoints += parseFloat(bestGrade.finalGrade || 0);
            }
          }
        }
        
        // 更新统计数据
        gradeStats.value = {
          ...gradeStats.value,
          totalCourses,
          passedCourses,
          totalCredits,
          averageGrade: totalCourses > 0 ? totalGradePoints / totalCourses : 0
        };
        
        console.log('更新后的成绩统计:', gradeStats.value);
      } catch (error) {
        console.error('处理补考信息失败:', error)
      }
    }
    
    // 获取教师课程
    const fetchTeacherCourses = async () => {
      if (props.role !== 'TEACHER') return
      
      loading.value = true
      try {
        // 确保teacherId是字符串类型
        const teacherIdStr = props.userId.toString();
        
        console.log('获取教师课程，teacherId:', teacherIdStr);
        const response = await axios.get(`/api/teacher/courses?teacherId=${teacherIdStr}`)
        teacherCourses.value = response.data || []
        
        // 标准化课程ID为字符串类型
        teacherCourses.value.forEach(course => {
          if (course.id) {
            course.id = course.id.toString();
          }
        });
        
        console.log('教师课程数据:', teacherCourses.value);
        
        // 如果有课程，默认选择第一个
        if (teacherCourses.value.length > 0) {
          selectedCourseId.value = teacherCourses.value[0].id.toString();
          fetchCourseStudents(selectedCourseId.value)
        }
      } catch (error) {
        console.error('获取教师课程失败:', error)
        ElMessage.error('获取课程信息失败')
      } finally {
        loading.value = false
      }
    }
    
    // 获取课程学生列表（包含成绩）
    const fetchCourseStudents = async (courseId) => {
      if (!courseId) return
      loading.value = true
      try {
        const courseIdStr = courseId.toString();
        const teacherIdStr = props.userId.toString();
        const response = await axios.get(`/api/teacher/courses/${courseIdStr}/grades?teacherId=${teacherIdStr}`)
        let students = response.data || [];
        // 合并同一学生同一门课的成绩，优先补考
        const studentMap = {}
        for (const student of students) {
          const key = student.studentId
          if (!studentMap[key] || (student.semester && student.semester.includes('补考'))) {
            studentMap[key] = student
          }
        }
        courseStudents.value = Object.values(studentMap).map(student => {
          if (student.studentId) {
            student.studentId = student.studentId.toString();
          }
          const processedStudent = {
            ...student,
            studentNumber: student.username || student.studentNumber || '',
            studentName: student.realName || student.studentName || ''
          };
          return processedStudent;
        });
        originalGrades.value = {}
        courseStudents.value.forEach(student => {
          if (student.studentId) {
            student.studentId = student.studentId.toString();
          }
          originalGrades.value[student.studentId] = {
            regularGrade: student.regularGrade,
            examGrade: student.examGrade,
            finalGrade: student.finalGrade
          }
        })
        hasChanges.value = false
      } catch (error) {
        console.error('获取课程学生列表失败:', error)
        ElMessage.error('获取学生列表失败')
      } finally {
        loading.value = false
      }
    }
    
    // 处理课程选择变更
    const handleCourseChange = (courseId) => {
      selectedCourseId.value = courseId
      fetchCourseStudents(courseId)
    }
    
    // 处理成绩输入变更
    const handleGradeChange = (student) => {
      // 计算最终成绩
      if (student.regularGrade !== null && student.examGrade !== null) {
        student.finalGrade = calculateFinalGrade(student)
      }
      
      // 检查是否有变更
      checkForChanges()
    }
    
    // 计算最终成绩
    const calculateFinalGrade = (student) => {
      if (student.regularGrade === null || student.examGrade === null) {
        return student.finalGrade !== null ? student.finalGrade : '未录入'
      }
      
      const regularWeight = 0.4 // 平时成绩权重
      const examWeight = 0.6 // 期末成绩权重
      
      return Math.round(student.regularGrade * regularWeight + student.examGrade * examWeight)
    }
    
    // 检查是否有成绩变更
    const checkForChanges = () => {
      hasChanges.value = courseStudents.value.some(student => isGradeChanged(student))
    }
    
    // 判断单个学生成绩是否有变更
    const isGradeChanged = (student) => {
      const original = originalGrades.value[student.studentId]
      if (!original) return true
      
      return student.regularGrade !== original.regularGrade ||
             student.examGrade !== original.examGrade
    }
    
    // 保存单个学生成绩
    const saveGrade = async (student) => {
      try {
        // 确保ID类型一致性
        const studentIdStr = student.studentId.toString();
        const courseIdStr = selectedCourseId.value.toString();
        const teacherIdStr = props.userId.toString();
        
        const gradeData = {
          studentId: studentIdStr,
          courseId: courseIdStr,
          regularGrade: student.regularGrade,
          examGrade: student.examGrade,
          finalGrade: calculateFinalGrade(student)
        }
        
        console.log('保存成绩数据:', gradeData);
        
        const response = await axios.post(
          `/api/teacher/courses/${courseIdStr}/grades?teacherId=${teacherIdStr}`,
          gradeData
        )
        
        if (response.data) {
          ElMessage.success('成绩保存成功')
          
          // 更新原始数据
          originalGrades.value[studentIdStr] = {
            regularGrade: student.regularGrade,
            examGrade: student.examGrade,
            finalGrade: student.finalGrade
          }
          
          checkForChanges()
        } else {
          ElMessage.error('成绩保存失败')
        }
      } catch (error) {
        console.error('保存成绩失败:', error)
        ElMessage.error('保存成绩失败')
      }
    }
    
    // 保存所有更改
    const saveAllGrades = async () => {
      try {
        // 确保courseId和teacherId是字符串类型
        const courseIdStr = selectedCourseId.value.toString();
        const teacherIdStr = props.userId.toString();
        
        // 筛选出有变更的成绩
        const changedGrades = courseStudents.value
          .filter(student => isGradeChanged(student))
          .map(student => ({
            studentId: student.studentId.toString(),
            courseId: courseIdStr,
            regularGrade: student.regularGrade,
            examGrade: student.examGrade,
            finalGrade: calculateFinalGrade(student)
          }))
        
        if (changedGrades.length === 0) {
          ElMessage.info('没有需要保存的更改')
          return
        }
        
        console.log('批量保存成绩数据:', changedGrades);
        
        const response = await axios.post(
          `/api/teacher/courses/${courseIdStr}/grades/batch?teacherId=${teacherIdStr}`,
          changedGrades
        )
        
        if (response.data) {
          ElMessage.success(`成功保存 ${changedGrades.length} 条成绩记录`)
          
          // 更新原始数据
          courseStudents.value.forEach(student => {
            if (isGradeChanged(student)) {
              const studentIdStr = student.studentId.toString();
              originalGrades.value[studentIdStr] = {
                regularGrade: student.regularGrade,
                examGrade: student.examGrade,
                finalGrade: calculateFinalGrade(student)
              }
            }
          })
          
          hasChanges.value = false
        } else {
          ElMessage.error('批量保存成绩失败')
        }
      } catch (error) {
        console.error('批量保存成绩失败:', error)
        ElMessage.error('批量保存成绩失败')
      }
    }
    
    // 重置单个学生成绩
    const resetGrade = (student) => {
      const original = originalGrades.value[student.studentId]
      if (original) {
        student.regularGrade = original.regularGrade
        student.examGrade = original.examGrade
        student.finalGrade = original.finalGrade
      }
      checkForChanges()
    }
    
    // 获取成绩状态文本
    const getStatusText = (student) => {
      if (student.finalGrade === null) {
        return '未评分'
      }
      return student.finalGrade >= 60 ? '通过' : '未通过'
    }
    
    // 获取成绩状态类型
    const getStatusType = (student) => {
      if (student.finalGrade === null) {
        return 'info'
      }
      return student.finalGrade >= 60 ? 'success' : 'danger'
    }
    
    // 获取成绩显示样式
    const getGradeClass = (grade) => {
      if (grade === null) return ''
      return grade < 60 ? 'failed-grade' : ''
    }
    
    // 格式化数字
    const formatNumber = (num) => {
      if (num === null || num === undefined) return '0.0'
      return parseFloat(num).toFixed(1)
    }
    
    // 搜索处理
    const handleSearch = () => {
      // 通过计算属性实现
    }
    
    // 处理管理员搜索
    const handleAdminSearch = () => {
      // 重置分页或其他操作
      console.log('管理员搜索:', adminSearchQuery.value, adminSemesterFilter.value)
    }
    
    // 管理员获取所有学生成绩数据
    const fetchAllStudentsGrades = async () => {
      if (props.role !== 'ADMIN') return
      adminLoading.value = true
      try {
        // 获取所有课程
        const coursesResponse = await axios.get('/api/admin/courses')
        adminCourses.value = coursesResponse.data
        // 获取所有学生
        const studentsResponse = await axios.get('/api/users/by-role?role=STUDENT')
        const students = studentsResponse.data
        // 为每个学生获取成绩
        const studentsWithGrades = []
        for (const student of students) {
          const studentInfo = {
            studentId: student.id,
            studentNumber: student.username,
            studentName: student.realName,
            major: student.major,
            grade: student.grade,
            passedCourses: 0,
            totalCourses: 0,
            totalGradePoints: 0
          }
          // 获取学生成绩
          try {
            const gradesResponse = await axios.get(`/api/users/me/grades?studentId=${student.id}`)
            const grades = gradesResponse.data
            // 合并同一门课的成绩，优先补考
            const courseMap = {}
            for (const grade of grades) {
              if (!courseMap[grade.courseId] || (grade.semester && grade.semester.includes('补考'))) {
                courseMap[grade.courseId] = grade
              }
            }
            
            // 获取补考状态
            try {
              const makeupResponse = await axios.get(`/api/makeup-exam/student?studentId=${student.id}`)
              const makeupExams = makeupResponse.data || []
              
              // 创建补考状态映射
              const makeupStatusMap = {}
              makeupExams.forEach(exam => {
                if (exam.status === '补考通过' || exam.status === '补考未通过') {
                  makeupStatusMap[exam.courseId] = {
                    status: exam.status,
                    score: exam.makeupScore
                  }
                  console.log(`学生${student.id}的课程${exam.courseId}补考状态: ${exam.status}, 分数: ${exam.makeupScore}`);
                }
              })
              
              // 更新成绩状态
              for (const courseId in courseMap) {
                const grade = courseMap[courseId]
                const makeupInfo = makeupStatusMap[courseId]
                if (makeupInfo && makeupInfo.status === '补考通过') {
                  grade.makeupPassed = true
                  console.log(`设置学生${student.id}的课程${courseId}为补考通过`);
                } else if (makeupInfo && makeupInfo.status === '补考未通过') {
                  grade.makeupFailed = true
                  console.log(`设置学生${student.id}的课程${courseId}为补考未通过`);
                }
              }
            } catch (error) {
              console.error(`获取学生 ${student.id} 的补考信息失败:`, error)
            }
            
            // 计算通过率和平均分
            let passedCount = 0
            let totalGradePoints = 0
            let gradeCount = 0
            for (const courseId in courseMap) {
              const grade = courseMap[courseId]
                              studentInfo['course_' + courseId] = grade.finalGrade
                studentInfo['semester_' + courseId] = grade.semester
                studentInfo['makeupPassed_' + courseId] = grade.makeupPassed || false
                studentInfo['makeupFailed_' + courseId] = grade.makeupFailed || false
                
                console.log(`学生${student.id}课程${courseId}的补考状态: 通过=${grade.makeupPassed}, 未通过=${grade.makeupFailed}`)
              
              if (grade.finalGrade !== null) {
                gradeCount++
                
                // 补考通过的课程，在平均分中按60分计算
                if (grade.makeupPassed) {
                  totalGradePoints += 60
                  passedCount++
                } else {
                  totalGradePoints += grade.finalGrade
                  if (grade.finalGrade >= 60) {
                    passedCount++
                  }
                }
              }
            }
            studentInfo.passedCourses = passedCount
            studentInfo.totalCourses = gradeCount
            studentInfo.passRate = gradeCount > 0 ? (passedCount / gradeCount) * 100 : 0
            studentInfo.averageGrade = gradeCount > 0 ? totalGradePoints / gradeCount : 0
            studentsWithGrades.push(studentInfo)
          } catch (error) {
            console.error(`获取学生 ${student.id} 的成绩失败:`, error)
            studentsWithGrades.push(studentInfo)
          }
        }
        adminStudents.value = studentsWithGrades
        // 按学号排序
        adminStudents.value.sort((a, b) => {
          if (a.studentNumber && b.studentNumber) {
            return a.studentNumber.localeCompare(b.studentNumber)
          }
          return 0
        })
      } catch (error) {
        console.error('获取学生成绩数据失败:', error)
        ElMessage.error('获取学生成绩数据失败')
      } finally {
        adminLoading.value = false
      }
    }
    
    let timer = null
    onMounted(() => {
      if (props.role === 'STUDENT') {
        fetchStudentGrades()
      } else if (props.role === 'TEACHER') {
        fetchTeacherCourses()
      } else if (props.role === 'ADMIN') {
        fetchAllStudentsGrades()
      }
      // 定时轮询刷新（根据角色自动适配）
      if (props.role === 'STUDENT' && typeof fetchStudentGrades === 'function') {
        timer = setInterval(() => {
          fetchStudentGrades()
        }, 5000)
      } else if (props.role === 'TEACHER' && typeof fetchTeacherCourses === 'function') {
        timer = setInterval(() => {
          fetchTeacherCourses()
        }, 5000)
      } else if (props.role === 'ADMIN' && typeof fetchAllStudentsGrades === 'function') {
        timer = setInterval(() => {
          fetchAllStudentsGrades()
        }, 5000)
      }
    })
    onUnmounted(() => {
      if (timer) clearInterval(timer)
    })
    
    return {
      // 学生相关
      studentGrades,
      gradeStats,
      filteredGrades,
      
      // 教师相关
      teacherCourses,
      selectedCourseId,
      courseStudents,
      hasChanges,
      
      // 通用
      loading,
      searchQuery,
      semesterFilter,
      
      // 管理员相关
      adminStudents,
      adminCourses,
      adminLoading,
      adminSearchQuery,
      adminSemesterFilter,
      filteredStudents,
      
      // 方法
      handleSearch,
      handleCourseChange,
      handleAdminSearch,
      getGradeClass,
      formatNumber,
      calculateFinalGrade,
      getStatusType,
      getStatusText,
      saveGrade,
      resetGrade,
      saveAllGrades,
      handleGradeChange,
      isGradeChanged,
      fetchAllStudentsGrades
    }
  }
}
</script>

<style scoped>
.grade-management {
  margin: 20px;
}

.statistics-cards {
  margin-bottom: 30px;
}

.stat-card {
  text-align: center;
  padding: 10px;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #409EFF;
}

.stat-label {
  font-size: 14px;
  color: #606266;
  margin-top: 5px;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.filter-bar {
  display: flex;
  align-items: center;
}

.grade-excellent {
  color: #67C23A;
  font-weight: bold;
}

.grade-good {
  color: #409EFF;
  font-weight: bold;
}

.grade-medium {
  color: #E6A23C;
}

.grade-pass {
  color: #909399;
}

.grade-fail {
  color: #F56C6C;
  font-weight: bold;
}

.earned-credits {
  color: #67C23A;
  font-weight: bold;
}

.course-selection {
  margin-bottom: 20px;
}

.action-buttons {
  display: flex;
  gap: 10px;
}
</style>